package com.easyui.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.easyui.bean.Student;
import com.easyui.common.SelNote;
import com.easyui.common.SelProject;
import com.easyui.common.SelStudent;

public class MainReplyServlet extends HttpServlet {
       
    public MainReplyServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
		

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
		String msg = "";
		boolean success = true;
		boolean upSuccess = true;
		List<Map> attachFile = null;
		
		HttpSession session = request.getSession(); //获的session
		String role = (String)session.getAttribute("role");
		String userID = (String)session.getAttribute("userID");
		
		if(role != null && !role.trim().equals("")) {
			if(userID != null && !userID.trim().equals("")) {//session未过期

				// Create a factory for disk-based file items
				DiskFileItemFactory disk = new DiskFileItemFactory();
				// 当上传文件太大时，因为虚拟机能使用的内存是有限的，所以此时要通过临时文件来实现上传文件的保存
				// 此方法是设置是否使用临时文件的临界值（单位：字节）
				disk.setSizeThreshold(1024 * 5);// 设置上传缓冲区容量为5k
		
				String servletPath = this.getServletContext().getRealPath("/");// 获得服务器所在地址
				String tempFile = "tempFile";
				String saveFile = "uploadFile";
				String tempPath = servletPath + tempFile;//临时文件路径
				String savePath = servletPath + saveFile;//存放文件实际路径
				
				//System.out.println(path);
				File tfile = new File(tempPath);
				if (!tfile.exists()) {
					tfile.mkdirs();
				}
				
				File sfile = new File(savePath);
				if (!sfile.exists()) {
					sfile.mkdirs();
				}
				// 设置临时文件的路径（绝对路径）
				disk.setRepository(tfile);
		
				// 创建能够解析上传文件的二进制流的类
				ServletFileUpload sfu = new ServletFileUpload(disk);
				long maxsize = 1024 * 1024 * 100;
				sfu.setSizeMax(maxsize);// 限制最大上传容量为100M
		
				List<FileItem> list = null;
				try {
					list = sfu.parseRequest(request);
				} catch (FileUploadException e) {
					success = false;
				}
		
				Iterator it = null;
		
				try {
					it = list.iterator();
				} catch (NullPointerException e) {
					out.println("<script language='javascript'>");
					out.println("$.messager.alert('添加项目失败','不支持你所上传文件的类型','error');");
					out.println("</script>");
					success = false;
				}
		
				if (success  && it != null) {
					String ncont = "";
					int rootid = -1;
					int pno = -1;
					int replysize = 0;//主题帖是否有回复
					attachFile = new ArrayList<Map>();
					while (it.hasNext()) {
						FileItem fileItem = (FileItem) it.next();
		
						if (fileItem.isFormField()) {// 为表单域
							String name = fileItem.getFieldName();
							String value = new String(fileItem.getString().getBytes("ISO-8859-1"), "utf-8");
							System.out.println(name + ":" + value);
							value.replace("\r\n", "<br>");
							System.out.println(value);
							if (name.equals("ncont")) {
								ncont = value;
							}
							if (name.equals("rootid")) {
								rootid = Integer.parseInt(value);
							}
							if (name.equals("pno")) {
								pno = Integer.parseInt(value);
							}
							if (name.equals("replysize")) {
								replysize = Integer.parseInt(value);
							}
						} else { // 为文件上传域
							String locPath = fileItem.getName();// 上传文件所在的本机的绝对路径
							System.out.println(locPath);
							if (!locPath.equals("")) {// 上传文件路径不为空
								
								// 获得上传文件的文件名
								int index = locPath.lastIndexOf("\\");
								String fileName = locPath.substring(index + 1);//文件的实际文件名，下载时候设置头信息用
								
								String saveName = "";//保存在服务器上的文件名，由日期+随机数+后缀组成
								SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
								saveName += sdf.format(new java.util.Date());
								
								for(int i=0; i<6; i++) {//得到6位10以内的随机数
									Random random = new Random();
									int r = random.nextInt(10);
									saveName += r;
								}
								
								//得到有后缀名的用来保存在服务器上的整个文件名
								index = locPath.lastIndexOf(".");
								saveName += locPath.substring(index);
								
								long filesize = fileItem.getSize();
								System.out.println("filesize:" + filesize);
							
								String serverPath = savePath + "\\" + saveName;// 文件上传到服务器端的绝对路径
								System.out.println(serverPath);
								System.out.println("savename:" + saveName);
								System.out.println("fileName:" +  fileName);
								
								File f = new File(serverPath);
								
								/*try {
									fileItem.write(f);
								} catch (Exception e) {
									e.printStackTrace();
								}*/
								
								FileOutputStream fos = new FileOutputStream(f);
		
								if (fileItem.isInMemory()) {
									try {
										fos.write(fileItem.get());
										upSuccess = true;
									} catch (IOException e) {
										e.printStackTrace();
										upSuccess = false;
									} finally {
										fos.close();
									}
								} else {
									InputStream is = null;
									try {
										is = fileItem.getInputStream();
										int i = -1;// 文件是否读完标志
										byte[] b = new byte[1024];
										i = is.read(b);
										while (i > 0) {
											fos.write(b, 0, i);
											i = is.read(b);
										}
										upSuccess = true;
									} catch (IOException e) {
										e.printStackTrace();
										upSuccess = false;
									} finally {
										is.close();
										fos.flush();
										fos.close();
									}
								}
								
								
								System.out.println("upsuc:" + upSuccess);
								if (upSuccess) {	//将附件信息添加到附件链表中
									Map<String, String> map = new HashMap<String, String>();
									map.put("fileName", fileName);
									map.put("saveName", saveName);
									map.put("filesize", "" + filesize);
									map.put("comment", "");
									attachFile.add(map);
									System.out.println("有附件1");
								} else {
									upSuccess = false;
									break;
								}
							}///上传为文件路径不为空结束
						}//上传 为文本域结束
					}//while结束
					
					if(upSuccess) {
						success = new SelNote().addMainReply(role, userID, pno, ncont, rootid, rootid, attachFile, replysize);
					} else {
						success = false;
					}
					
				}
				
			} else {
				success = false;
			}
		} else {
			success = false;
		}
			
		if(success) {
			msg = "ok";
		} else {
			msg = "error";
		}
		out.print(msg);
		out.flush();
		out.close();
	}

}
